package com.whisperly.echotalk.starryb.schemas;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.LoudnessEnhancer;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.whisperly.echotalk.bllmodel.ChatContentAdapter;
import com.whisperly.echotalk.bllmodel.ChatHistory;
import com.whisperly.echotalk.bllmodel.ChatWithUser;
import com.whisperly.echotalk.bllmodel.UserQuery;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.other.Settings;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.Flash;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.SaveListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AI extends AppCompatActivity {

    public ListView listView;
    public EditText et_send_msg;
    public Button btn_send;
    public ChatContentAdapter adapter;
    private Toast currentToast;

    private List<ChatWithUser> chatBeanList = new ArrayList<>();;
    private String welcome[];
    private String sendMsg;
    private int count = 0;
    private ChatWithUser chatWithUser;

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private int MSG_OK = 1;
    private long exitTime = 0;
    private int position;
    private UserWithChat user = new UserWithChat();

    private static final String FREE = "https://api.ownthink.com/bot";
    private static final String KEY = "d4c4e406e582ebd2488e1aa0055d76e0";
    private static final String APP_ID = "GAI2dN31";
    private static final String LOGIN = "https://api.chatkore.com/v1/chat/completions";
    private static final String CONTENT_TYPE = "application/json";
    private static final String AUTHORIZATION = "Bearer sk-p5ir9HefTt0lPlH8dVGtnZBDugcewfGtYWma9RXSRlD3u7dB";

    private static final String PREFS_NAME = "AI";
    private static final String PREFS_COUNT_FREE = "Free";
    private static final String PREFS_COUNT_LOGIN = "Login";
    private static final String PREFS_DATE = "date";

    private View sigup_view;
    private View comparision_view;
    private AlertDialog write;

    private TextView signup;

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppsManager.addActivity(this);
        setContentView(R.layout.aimain);
        Toolbar infoToolbar = findViewById(R.id.toolbar);
        user = GlobalData.getUser();
        setSupportActionBar(infoToolbar);
        ActionBar infoActionBar = getSupportActionBar();
        if (infoActionBar != null) {
            infoActionBar.setDisplayShowTitleEnabled(false); // 不显示默认标题
        }
        TextView toolbarTitle = findViewById(R.id.toolbar_title);
        toolbarTitle.setText(R.string.toolbar_title);

        listView = (ListView) findViewById(R.id.list);
        et_send_msg = (EditText) findViewById(R.id.send_msg);
        btn_send = (Button) findViewById(R.id.send);
        welcome = getResources().getStringArray(R.array.welcome);
        signup = findViewById(R.id.signup);

        sp = getSharedPreferences("SignUp", MODE_PRIVATE);
        editor = sp.edit();

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!GlobalData.getUsername().equals("")) {
                    setSignup();
                } else {
                    showLoginAlertDialog();
                }
            }
        });
        if (user.getObjectId() != null) {
            Log.e("objectId", user.toString());
            BmobQuery<UserWithChat> userWithChatBmobQuery = new BmobQuery<>();
            userWithChatBmobQuery.getObject(user.getObjectId(), new QueryListener<UserWithChat>() {
                @Override
                public void done(UserWithChat userWithChat, BmobException e) {
                    if (e == null) {
                        Log.e("UserWithChat", "获取到聊天记录");
                        BmobQuery<ChatHistory> bmobQuery = new BmobQuery<>();
                        bmobQuery.findObjects(new FindListener<ChatHistory>() {
                            @Override
                            public void done(List<ChatHistory> list, BmobException e) {
                                if (e == null){
                                    if (list.isEmpty()) {
                                        showFirstMessage();
                                        return;
                                    }
                                    for (ChatHistory chatHistory : list) {
                                        if (chatHistory.getUser_id().equals(user.getObjectId())) {
                                            ChatWithUser chatWithUser1 = new ChatWithUser();
                                            chatWithUser1.setState(chatHistory.getState());
                                            chatWithUser1.setMessage(chatHistory.getMessage());
                                            chatBeanList.add(chatWithUser1);
                                        }
                                    }
                                    adapter.notifyDataSetChanged();
                                    showFirstMessage();
                                }else {
                                    Log.e("e", e.toString());
                                }
                            }
                        });
                    } else {
                        Log.e("e", "网络异常");
                    }
                }
            });
        }else {
            position = (int) (Math.random() * welcome.length);
            Log.e("welcome[position]",welcome[position]);
            showData(welcome[position]);
        }

        if (chatBeanList == null) {
            chatBeanList = new ArrayList<>();
        }
        adapter = new ChatContentAdapter(this, chatBeanList);
        listView.setAdapter(adapter);
        btn_send.setOnClickListener(v -> sendData());
        et_send_msg.setOnKeyListener((v, keyCode, keyEvent) -> {
            if ((keyCode == KeyEvent.KEYCODE_ENTER) && (keyEvent.getAction() == KeyEvent.ACTION_DOWN)) {
                sendData();
            }
            return false;
        });

        FloatingActionButton floatingActionButton = findViewById(R.id.float_collection);
        floatingActionButton.setOnTouchListener(new View.OnTouchListener() {
            private float initialX, initialY;
            private float initialTouchX, initialTouchY;
            private final int screenWidth = getResources().getDisplayMetrics().widthPixels;

            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = view.getX();
                        initialY = view.getY();
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float deltaX = event.getRawX() - initialTouchX;
                        float deltaY = event.getRawY() - initialTouchY;
                        float newX = initialX + deltaX;
                        float newY = initialY + deltaY;
                        newX = Math.max(0, Math.min(newX, screenWidth - view.getWidth()));
                        newY = Math.max(0, Math.min(newY, getResources().getDisplayMetrics().heightPixels - view.getHeight()));
                        view.setX(newX);
                        view.setY(newY);
                        return true;
                    case MotionEvent.ACTION_UP:
                        float center = screenWidth / 2f;
                        float finalX = view.getX() + view.getWidth() / 2f > center ? screenWidth - view.getWidth() : 0;
                        view.animate()
                                .x(finalX)
                                .setDuration(200)
                                .start();

                        if (Math.abs(event.getRawX() - initialTouchX) < 10 && Math.abs(event.getRawY() - initialTouchY) < 10) {
                            view.performClick();
                        }
                        return true;
                }
                return false;
            }

        });

        floatingActionButton.performClick();
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tips();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    private void showFirstMessage() {
        if (user.getObjectId() != null) {
            ChatHistory chatHistory = new ChatHistory(user.getObjectId(), welcome[position], ChatWithUser.RECEIVE);
            BmobQuery<ChatHistory> chatHistoryBmobQuery = new BmobQuery<>();
            chatHistoryBmobQuery.doSQLQuery("select * from ChatHistory where userId = '" + user.getObjectId() + "'", new SQLQueryListener<ChatHistory>() {
                @Override
                public void done(BmobQueryResult<ChatHistory> bmobQueryResult, BmobException e) {
                    if (e == null){
                        List<ChatHistory> results = bmobQueryResult.getResults();
                        if (results.isEmpty()){
                            chatHistory.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e != null) {
                                        Log.e("e1", e.toString());
                                    }
                                }
                            });
                        }else {
                            position = (int) (Math.random() * welcome.length);
                            showData(welcome[position]);
                            Log.e("e","notEmpty");
                        }
                    }else {
                        Log.e("e",bmobQueryResult.getResults().toString());
                    }
                }
            });
        }else {
            position = (int) (Math.random() * welcome.length);
            showData(welcome[position]);
        }
    }

    private void getDataFromServerForFree() {
        OkHttpClient okHttpClient = new OkHttpClient();

        try {
            String encodeMsg = URLEncoder.encode(sendMsg, "UTF-8");
            Request request = new Request.Builder()
                    .url(FREE + "?key=" + KEY + "&appid=" + APP_ID + "&spoken=" + encodeMsg)
                    .build();
            Call call = okHttpClient.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                    handler.post(() -> {
                        btn_send.setEnabled(true);
                        btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                        showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
                    });
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String res = response.body() != null ? response.body().string() : null;
                    Message msg = new Message();
                    msg.what = MSG_OK;
                    msg.obj = res;
                    handler.sendMessage(msg);
                }
            });
        } catch (Exception e) {
            handler.post(() -> {
                btn_send.setEnabled(true);
                btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
            });
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == 1) {
                if (msg.obj != null) {
                    String result = (String) msg.obj;
                    Log.i("handler", result);
                    paresData(result);
                }
            }
        }
    };

    private void paresData(String content) {
        try {
            JSONObject jsonObject = new JSONObject(content);
            JSONObject data = jsonObject.getJSONObject("data");
            String resContent = data.getJSONObject("info").getString("text");
            resContent = resContent.replace("{br}", "\n");
            int code = data.getInt("type");
            Log.i("paresData", resContent + "," + code);
            updateView(code, resContent);
            btn_send.setEnabled(true);
            btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
            if (user.getObjectId() != null) {
                ChatHistory chatHistory = new ChatHistory();
                chatHistory.setUser_id(user.getObjectId());
                chatHistory.setMessage(resContent);
                chatHistory.setState(ChatWithUser.RECEIVE);
                chatHistory.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e != null) {
                            Log.e("e2", e.toString());
                        }
                    }
                });
            }
        } catch (JSONException e) {
            handler.post(() -> {
                btn_send.setEnabled(true);
                btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
            });
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                if (currentToast != null) {
                    currentToast.cancel();
                }

                currentToast = Toast.makeText(AI.this, R.string.Press_again_to_exit_the_program, Toast.LENGTH_SHORT);
                currentToast.show();

                exitTime = System.currentTimeMillis();
            } else {
                AI.this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void getDataFromServerForLoginUser() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(Looper.getMainLooper());

        try {
            sendMsg = URLEncoder.encode(sendMsg, "utf-8");
        } catch (UnsupportedEncodingException e) {
            handler.post(() -> {
                btn_send.setEnabled(true);
                btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
            });
            e.printStackTrace();
        }

        executor.execute(() -> {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse(CONTENT_TYPE);
            RequestBody body = RequestBody.create(mediaType, "{\n\"model\": \"gpt-3.5-turbo\",\n\"messages\": [{\"role\": \"user\", \"content\": \"" + sendMsg + "\"}],\n\"temperature\": 0.7\n}");
            Request request = new Request.Builder()
                    .url(LOGIN)
                    .post(body)
                    .addHeader("Content-Type", CONTENT_TYPE)
                    .addHeader("Authorization", AUTHORIZATION)
                    .build();

            try {
                try (Response response = client.newCall(request).execute()) {
                    String responseBody = Objects.requireNonNull(response.body()).string();
                    Log.i("responseBody", responseBody);

                    handler.post(() -> {
                        try {
                            JSONObject jsonObject = new JSONObject(responseBody);
                            Log.i("jsonObject", jsonObject.toString());
                            JSONArray choicesArray = jsonObject.getJSONArray("choices");
                            for (int i = 0; i < choicesArray.length(); i++) {
                                JSONObject choice = choicesArray.getJSONObject(i);
                                JSONObject messageObject = choice.getJSONObject("message");
                                String content = messageObject.getString("content");
                                Log.i("content", content);
                                updateView(1, content);
                                btn_send.setEnabled(true);
                                btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                                if (user.getObjectId() != null) {
                                    ChatHistory chatHistory = new ChatHistory();
                                    chatHistory.setUser_id(user.getObjectId());
                                    chatHistory.setMessage(content);
                                    chatHistory.setState(ChatWithUser.RECEIVE);
                                    chatHistory.save(new SaveListener<String>() {
                                        @Override
                                        public void done(String s, BmobException e) {
                                            if (e != null) {
                                                Log.e("e3", e.toString());
                                            }
                                        }
                                    });
                                }
                            }
                        } catch (JSONException e) {
                            handler.post(() -> {
                                btn_send.setEnabled(true);
                                btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                                showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
                            });
                            e.printStackTrace();
                        }
                    });

                    if (!response.isSuccessful()) {
                        handler.post(() -> {
                            btn_send.setEnabled(true);
                            btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                            showData(getString(R.string.Master_I_have_a_fault_please_try_again_later));
                        });
                        throw new IOException("Unexpected code " + response);
                    }
                }
            } catch (IOException e) {
                handler.post(() -> {
                    btn_send.setEnabled(true);
                    btn_send.setBackgroundResource(R.drawable.ic_send_pressed);
                    showCenteredToast(getString(R.string.Master_I_have_a_fault_please_try_again_later));
                });
                e.printStackTrace();
            }
        });
    }

    private void updateView(int code, String content) {
        switch (code) {
            case 4094:
                showData(getString(R.string.Master1));
                break;
            case 40005:
                showData(getString(R.string.Master2));
                break;
            case 40886:
                showData(getString(R.string.Master3));
                break;
            case 40807:
                showData(getString(R.string.Master4));
                break;
            case 102:
                showData(getString(R.string.Master5));
                break;
            default:
                showData(content);
                break;
        }
    }

    private void showData(String message) {
        ChatWithUser chatBean = new ChatWithUser();
        chatBean.setMessage(message);
        chatBean.setState(ChatWithUser.RECEIVE);
        Log.e("chatBean",chatBean.toString());
        chatBeanList.add(chatBean);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        } else {
            adapter = new ChatContentAdapter(this, chatBeanList);
            listView.setAdapter(adapter);
        }

    }

    private void sendData() {
        sendMsg = et_send_msg.getText().toString();
        if (TextUtils.isEmpty(sendMsg)) {
            if (currentToast != null) {
                currentToast.cancel();
            }

            currentToast = Toast.makeText(this, R.string.You_havent_entered_any_information_yet, Toast.LENGTH_SHORT);
            currentToast.show();

            return;
        }

        if (!btn_send.isEnabled()) {
            showCenteredToast(getString(R.string.Please_try_again_later));
            return;
        }

        btn_send.setEnabled(false);
        btn_send.setBackgroundResource(R.drawable.ic_send);
        et_send_msg.setText("");

        chatWithUser = new ChatWithUser();
        chatWithUser.setMessage(sendMsg);
        chatWithUser.setState(ChatWithUser.SEND);
        chatBeanList.add(chatWithUser);
        adapter.notifyDataSetChanged();
        if (user.getObjectId() != null) {
            ChatHistory chatHistory = new ChatHistory();
            chatHistory.setUser_id(user.getObjectId());
            chatHistory.setMessage(sendMsg);
            chatHistory.setState(ChatWithUser.SEND);
            chatHistory.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e != null) {
                        Log.e("e4", e.toString());
                    }
                }
            });

            UserQuery userQuery = new UserQuery();
            userQuery.setUser_id(user.getObjectId());
            userQuery.setQueries(sendMsg);
            userQuery.setDate(getCurrentDate());
            userQuery.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e != null) {
                        Log.e("e5", e.toString());
                    }
                }
            });
        }

        BmobQuery<UserWithChat> query = new BmobQuery<>();
        query.doSQLQuery("select * from UserWithChat where name='" + GlobalData.getUsername() + "'", new SQLQueryListener<UserWithChat>() {
            @Override
            public void done(BmobQueryResult<UserWithChat> bmobQueryResult, BmobException e) {
                if (e == null) {
                    List<UserWithChat> results = bmobQueryResult.getResults();
                    checkAndUpdateCount(!results.isEmpty());
                } else {
                    Log.e("e6", e.toString());
                }
            }
        });
    }

    private void checkAndUpdateCount(boolean isLoginUser) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String savedDate = prefs.getString(PREFS_DATE, "");
        String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

        int countFree = prefs.getInt(PREFS_COUNT_FREE, 0);
        int countLogin = prefs.getInt(PREFS_COUNT_LOGIN, 0);

        if (!currentDate.equals(savedDate)) {

            countFree = 0;
            countLogin = 0;
            prefs.edit().putString(PREFS_DATE, currentDate).apply();
        }

        if (isLoginUser) {
            if (countLogin >= 50) {

                showLimitReachedDialog(true);
                return;
            }
            prefs.edit().putInt(PREFS_COUNT_LOGIN, countLogin + 1).apply();
            getDataFromServerForLoginUser();
        } else {
            if (countFree >= 10) {

                showLimitReachedDialog(false);
                return;
            }
            prefs.edit().putInt(PREFS_COUNT_FREE, countFree + 1).apply();
            getDataFromServerForFree();
        }
    }

    private void showLimitReachedDialog(boolean isRegisteredUser) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.Limit_Reached);

        if (isRegisteredUser) {
            builder.setMessage(R.string.tomorrow);
        } else {
            builder.setMessage(R.string.Please_register_to_continue_using_the_service);
        }

        builder.setPositiveButton(R.string.OK, (dialog, which) -> dialog.dismiss());


        if (!isRegisteredUser) {
            builder.setNegativeButton(R.string.Register, (dialog, which) -> {

                Intent intent = new Intent(this, Register.class);
                startActivity(intent);
            });
        }

        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private String getCurrentDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        return dateFormat.format(new Date());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Flash.isFlag()) {
            chatBeanList.clear();
            Log.e("eeee", "我刷新了");
            showFirstMessage();
            Flash.setFlag(false);
        }
    }

    private void showCenteredToast(String message) {
        if (currentToast != null) {
            currentToast.cancel();
        }

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.customize_toast,
                findViewById(R.id.custom_toast_container));

        TextView text = layout.findViewById(R.id.text);
        text.setText(message);

        currentToast = new Toast(getApplicationContext());
        currentToast.setGravity(Gravity.CENTER, 0, 0);
        currentToast.setDuration(Toast.LENGTH_SHORT);
        currentToast.setView(layout);
        currentToast.show();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_settings) {

            Intent intent = new Intent(this, Settings.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    public void setSignup() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String today = sdf.format(new Date());


        String lastSignUpDate = sp.getString("lastSignUpDate", "");

        if (!today.equals(lastSignUpDate)) {
            count++;


            write = new AlertDialog.Builder(this).create();
            sigup_view = LayoutInflater.from(this).inflate(R.layout.signup, null);
            write.setView(sigup_view);
            write.show();


            editor.putString("singUp", Integer.toString(count));
            editor.putString("lastSignUpDate", today);
            editor.commit();
        } else {

            Toast.makeText(this, R.string.You_have_already_signed_up_today, Toast.LENGTH_SHORT).show();
        }
    }

    public void tips() {

        write = new AlertDialog.Builder(this).create();
        comparision_view = LayoutInflater.from(this).inflate(R.layout.comparison, null);
        write.setView(comparision_view);
        write.show();
    }

    private void showLoginAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false).setCancelable(false)
                .show();
    }


}
